#include "SafeDataFile.h"

#include <unistd.h>

#include "common.h"
#include "Log.h"
#include "ErrorCode.h"

ssize_t SafeDataFile::read (void *buffer, size_t size) {
    int32_t count = FILE_RETRY_COUNT;
    ssize_t processed = -1;
    do {
        processed = ::read(deviceFd, buffer, size);
    } while(0 > processed && --count);

    if (0 > processed) {
        std::string message = deviceName;
        message.append(",read failed,");
        LOG_ERROR(buildErrorMessage(processed, errno, message).data());
    }

    return processed;
}

/* Write N bytes of BUF to FD.  Return the number written, or -1.
   This function is a cancellation point and therefore not marked with
   __THROW.  */
ssize_t SafeDataFile::write (const void *buffer, const size_t size) {
    int32_t count = FILE_RETRY_COUNT;
    ssize_t processed = -1;
    ssize_t allWritten = 0;
    const uint8_t* pData = reinterpret_cast <const uint8_t*>(buffer);
    do {
        count = FILE_RETRY_COUNT;
        do {
            processed = ::write(deviceFd, pData + allWritten, size - allWritten);
        } while(0 > processed && --count);
        if (0 < processed) {
            allWritten += processed;
        } else {
            break;
        }
    } while (allWritten != size);

    if (allWritten != size) {
        std::string message = deviceName;
        message.append(",write failed,");
        LOG_ERROR(buildErrorMessage(processed, errno, message).data());
    }

    return allWritten;
}










